#include "dragframe.h"
//#include <QtWidgets>

DragFrame::DragFrame(QWidget* parent, int id)
    : QFrame(parent)
{
    this->resize(150, 310);
    this->setStyleSheet("background-color: teal;border-radius:4px;");
    //this->setStyleSheet("background-color: rgb(7, 34, 31);border-radius:4px;");
    fid = id;
    // modbus地址栏
    modbusAddr = new QLabel(parent);
    modbusAddr->setText("Modbus:*");
    modbusAddr->setFrameShape(QFrame::WinPanel);
    modbusAddr->setAlignment(Qt::AlignCenter);
    modbusAddr->setStyleSheet("background-color:darkslategrey;font: 12pt;color: yellow;");
    // A通道传感器安装地方显示
    addrA = new QLabel;
    addrA->setText("未使用");
    addrA->setFrameShape(QFrame::Box);
    addrA->setAlignment(Qt::AlignCenter);
    addrA->setStyleSheet("background-color:gray;color:white;");
    // A通道浓度值
    cha_value = new QLabel(this);
    cha_value->setText("<font><b></b></font><font size='-4'></font>");
    cha_value->setFrameShape(QFrame::Box);
    cha_value->setFrameShadow(QFrame::Raised);
    cha_value->setAlignment(Qt::AlignCenter);
    cha_value->setStyleSheet("background:palegreen;font: 14pt, bold;");
    //cha_value->setStyleSheet("background-color: rgb(0,0,0);color: rgb(85, 255, 0);font: 14pt, bold;");
    al = new QLabel(this);
    al->setText("预报");
    al->setFrameShape(QFrame::Box);
    al->setAlignment(Qt::AlignCenter);
    al->setStyleSheet("background-color:darkred;");
    ah = new QLabel(this);
    ah->setText("高报");
    ah->setFrameShape(QFrame::Box);
    ah->setAlignment(Qt::AlignCenter);
    ah->setStyleSheet("background-color:darkred;");
    ac = new QLabel(this);
    ac->setText("小心");
    ac->setFrameShape(QFrame::Box);
    ac->setAlignment(Qt::AlignCenter);
    ac->setStyleSheet("background-color:darkred;");
    af = new QLabel(this);
    af->setText("故障");
    af->setFrameShape(QFrame::Box);
    af->setAlignment(Qt::AlignCenter);
    af->setStyleSheet("background-color:darkred;");
    // B通道传感器安装地方显示
    addrB = new QLabel(this);
    addrB->setText("未使用");
    addrB->setFrameShape(QFrame::Box);
    addrB->setAlignment(Qt::AlignCenter);
    addrB->setStyleSheet("background-color:gray;color:white;");
    // B通道浓度值
    chb_value = new QLabel(this);
    chb_value->setText("<font><b></b></font><font size='-4'></font>");
    chb_value->setFrameShape(QFrame::Box);
    chb_value->setFrameShadow(QFrame::Raised);
    chb_value->setAlignment(Qt::AlignCenter);
    chb_value->setStyleSheet("background-color:palegreen;font: 14pt, bold;");
    bl = new QLabel(this);
    bl->setText("预报");
    bl->setFrameShape(QFrame::Box);
    bl->setAlignment(Qt::AlignCenter);
    bl->setStyleSheet("background-color:darkred;");
    bh = new QLabel(this);
    bh->setText("高报");
    bh->setFrameShape(QFrame::Box);
    bh->setAlignment(Qt::AlignCenter);
    bh->setStyleSheet("background-color:darkred;");
    bc = new QLabel(this);
    bc->setText("小心");
    bc->setFrameShape(QFrame::Box);
    bc->setAlignment(Qt::AlignCenter);
    bc->setStyleSheet("background-color:darkred;");
    bf = new QLabel(this);
    bf->setText("故障");
    bf->setFrameShape(QFrame::Box);
    bf->setAlignment(Qt::AlignCenter);
    bf->setStyleSheet("background-color:darkred;");
    gridLayout = new QGridLayout(this);
    gridLayout->setSpacing(3);
    gridLayout->setMargin(6);
    gridLayout->addWidget(modbusAddr, 0, 0, 1, 2);
    gridLayout->addWidget(addrA,      1, 0, 1, 2);
    gridLayout->addWidget(cha_value,  2, 0, 1, 2);
    gridLayout->addWidget(al,         3, 0, 1, 1);
    gridLayout->addWidget(ah,         3, 1, 1, 1);
    gridLayout->addWidget(ac,         4, 0, 1, 1);
    gridLayout->addWidget(af,         4, 1, 1, 1);
    gridLayout->addWidget(addrB,      5, 0, 1, 2);
    gridLayout->addWidget(chb_value,  6, 0, 1, 2);
    gridLayout->addWidget(bl,         7, 0, 1, 1);
    gridLayout->addWidget(bh,         7, 1, 1, 1);
    gridLayout->addWidget(bc,         8, 0, 1, 1);
    gridLayout->addWidget(bf,         8, 1, 1, 1);
    // [0]设置每行高度比率
    gridLayout->setRowStretch(0, 6);
    gridLayout->setRowStretch(1, 6);
    gridLayout->setRowStretch(2, 7);
    gridLayout->setRowStretch(3, 5);
    gridLayout->setRowStretch(4, 5);
    gridLayout->setRowStretch(5, 6);
    gridLayout->setRowStretch(6, 7);
    gridLayout->setRowStretch(7, 5);
    gridLayout->setRowStretch(8, 5);
    // [!0]
    setLayout(gridLayout);
    F1_8["NF"] = tr("no failure");
    F1_8["F1"] = tr("F1 电源线路故障");
    F1_8["F2"] = tr("F2 输入信号故障");
    F1_8["F3"] = tr("F3 存储器（EEPROM）程序出错");
    F1_8["F4"] = tr("F4 操作功能码时系统掉电");
    F1_8["F5"] = tr("F5 模拟信号相关的A/D转换器故障");
    F1_8["F6"] = tr("F6 存储器（RAM)故障");
    F1_8["F7"] = tr("F7 只读存储器（EPROM）产生错误");
    F1_8["F8"] = tr("F8 控制器内随机存储器数据设置发生错误");
}

// 设置Modbus地址
void DragFrame::setModbusAddr(int addr)
{
    modbusAddr->setText(QString("Modbus:%1").arg(addr));
    fmodbusAddr = addr;
}

// 设置AB通道传感器名称
//void DragFrame::setChabName(QString cha, QString chb)
//{
//    addrA->setText(cha);
//    addrB->setText(chb);
//}

// 显示通道超时状态
void DragFrame::dispTimeout()
{
    QSettings configIni(QCoreApplication::applicationDirPath() +
                        "/config.ini", QSettings::IniFormat);

    if(configIni.value("com/timeout", 1).toBool()) // 是否显示超时信息
    {
        cha_value->setText("<font color=red size='-4'>Timeout</font>");
        chb_value->setText("<font color=red size='-4'>Timeout</font>");
    }
    else
    {
        cha_value->setText("");
        chb_value->setText("");
    }
}

// 为CardInfo结构赋值,并将结果显示在界面上
void DragFrame::setValues(QVector<quint16> values)
{
    bool isAlarmSound = false;

    for(int i = 0, count = values.count(); i < count; i++)
    {
        ci.data[i] = values[i];  // 正常有24个数据
    }

    // 显示A、B通道浓度值
    if(!ci.state_fail_cha && !ci.state_drift_cha && !ci.state_eeee_cha && !ci.e1_cha && !ci.e2_cha &&
       !ci.e3_cha && !ci.e4_cha)
    {
        value_a = (ci.v_real_cha * 1.0) / qPow(10, ci.decimal_cha); // 值计算： value / (10^decimals)
        cha_value->setText(QString("<font><b>%1</b></font><font size='-4'>%2</font>").arg(QString::number(
                           value_a, 'f', ci.decimal_cha)).arg(unit_a));
        // 保存数据到数据库
        dbSaveRecode(QString("CHA%1 %2").arg(fid + 1).arg(chaAddr), value_a, unit_a);
        chJson["value_a"] = value_a;
        chJson["unit_a"] = unit_a;
    }

    if(!ci.state_fail_chb && !ci.state_drift_chb && !ci.state_eeee_chb && !ci.e1_chb && !ci.e2_chb &&
       !ci.e3_chb && !ci.e4_chb)
    {
        value_b = (ci.v_real_chb * 1.0) / qPow(10, ci.decimal_chb); // 值计算： value / (10^decimals)
        chb_value->setText(QString("<font><b>%1</b></font><font size='-4'>%2</font>").arg(QString::number(
                           value_b, 'f', ci.decimal_chb)).arg(unit_b));
        // 保存数据到数据库
        dbSaveRecode(QString("CHB%1 %2").arg(fid + 1).arg(chbAddr), value_b, unit_b);
        chJson["value_b"] = value_b;
        chJson["unit_b"] = unit_b;
    }

    // 是否有故障   0无故障 1～8故障F1～F8
    if((ci.state_fail_cha >= 1) && (ci.state_fail_cha <= 8))
    {
        QString fn = QString("F%1").arg(ci.state_fail_cha);
        cha_value->setText(fn);
        af->setStyleSheet("background:red");

        if(old_state_fail_cha == ci.state_fail_cha)
        {
            dbSaveAlarm(QString("CHA%1 %2").arg(fid + 1).arg(chaAddr), F1_8[fn]);
        }

        //emit playWarningSound(true);
        chJson["state_fail_cha"] = fn;
        old_state_fail_cha = ci.state_fail_cha;
        //isAlarmSound = true;
    }
    else
    {
        af->setStyleSheet("background:darkred");
        chJson["state_fail_cha"] = "";
        old_state_fail_cha = 0;
        //emit playWarningSound(false);
    }

    if((ci.state_fail_chb >= 1) && (ci.state_fail_chb <= 8))
    {
        QString fn = QString("F%1").arg(ci.state_fail_chb);
        chb_value->setText(fn);
        bf->setStyleSheet("background:red");

        if(old_state_fail_chb == ci.state_fail_chb)
        {
            dbSaveAlarm(QString("CHB%1 %2").arg(fid + 1).arg(chbAddr), F1_8[fn]);
        }

        //emit playWarningSound(true);
        chJson["state_fail_chb"] = fn;
        old_state_fail_chb = ci.state_fail_chb;
    }
    else
    {
        bf->setStyleSheet("background:darkred");
        chJson["state_fail_chb"] = "";
        old_state_fail_chb = 0;
        //emit playWarningSound(false);
    }

    // 是否超漂移   0无漂移 <>0漂移
    if(ci.state_drift_cha != 0)
    {
        if(old_state_drift_cha == 0)
        {
            dbSaveAlarm(QString("CHA%1 %2").arg(fid + 1).arg(chaAddr),
                        QString("DRIFT 漂移 %1").arg(ci.state_drift_cha));
        }

        chJson["state_drift_cha"] = "DRIFT 漂移";
        //emit playWarningSound(true);
        old_state_drift_cha = 1;
    }
    else
    {
        chJson["state_drift_cha"] = "";
        old_state_drift_cha = 0;
        //emit playWarningSound(false);
    }

    if(ci.state_drift_chb != 0)
    {
        if(old_state_drift_chb == 0)
        {
            dbSaveAlarm(QString("CHB%1 %2").arg(fid + 1).arg(chbAddr),
                        QString("DRIFT 漂移 %1").arg(ci.state_drift_chb));
        }

        chJson["state_drift_chb"] = "DRIFT 漂移";
        //emit playWarningSound(true);
        old_state_drift_chb = 1;
    }
    else
    {
        chJson["state_drift_chb"] = "";
        old_state_drift_chb = 0;
        //emit playWarningSound(false);
    }

    // 是否超量程   0没超量程 1超量程EEEE
    if(ci.state_eeee_cha == 1)
    {
        cha_value->setText("EEEE");
        chJson["state_eeee_cha"] = "EEEE 超量程";

        if(old_state_eeee_cha == 0)
        {
            dbSaveAlarm(QString("CHA%1 %2").arg(fid + 1).arg(chaAddr), "EEEE 超量程");
        }

        //emit playWarningSound(true);
        old_state_eeee_cha = 1;
    }
    else
    {
        chJson["state_eeee_cha"] = "";
        old_state_eeee_cha = 0;
        //emit playWarningSound(false);
    }

    if(ci.state_eeee_chb == 1)
    {
        chb_value->setText("EEEE");
        chJson["state_eeee_chb"] = "EEEE 超量程";

        if(old_state_eeee_chb == 0)
        {
            dbSaveAlarm(QString("CHB%1 %2").arg(fid + 1).arg(chbAddr), "EEEE 超量程");
        }

        //emit playWarningSound(true);
        old_state_eeee_chb = 1;
    }
    else
    {
        chJson["state_eeee_chb"] = "";
        old_state_eeee_chb = 0;
        //emit playWarningSound(false);
    }

    // 是否超量程   E1
    if(ci.e1_cha == 1)
    {
        cha_value->setText("E1");

        if(old_e1_cha == 0)
        {
            dbSaveAlarm(QString("CHA%1 %2").arg(fid + 1).arg(chaAddr),
                        "E1 零信号和满量程之间的信号差 <2mV");
            chJson["e1_cha"] = "E1 零信号和满量程之间的信号差 <2mV";
            old_e1_cha = 1;
        }
    }
    else
    {
        old_e1_cha = 0;
    }

    if(ci.e1_chb == 1)
    {
        chb_value->setText("E1");

        if(old_e1_chb == 0)
        {
            dbSaveAlarm(QString("CHB%1 %2").arg(fid + 1).arg(chbAddr),
                        "E1 零信号和满量程之间的信号差 <2mV");
            chJson["e1_chb"] = "E1 零信号和满量程之间的信号差 <2mV";
            old_e1_chb = 1;
        }
    }
    else
    {
        old_e1_chb = 0;
    }

    // 是否超量程   E2
    if(ci.e2_cha == 1)
    {
        cha_value->setText("E2");

        if(old_e2_cha == 0)
        {
            dbSaveAlarm(QString("CHA%1 %2").arg(fid + 1).arg(chaAddr),
                        "E2 零信号和满量程之间的信号差 >=200mV");
            chJson["e2_cha"] = "E2 零信号和满量程之间的信号差 >=200mV";
            old_e2_cha = 1;
        }
    }
    else
    {
        old_e2_cha = 0;
    }

    if(ci.e2_chb == 1)
    {
        chb_value->setText("E2");

        if(old_e2_chb == 0)
        {
            dbSaveAlarm(QString("CHB%1 %2").arg(fid + 1).arg(chbAddr),
                        "E2 零信号和满量程之间的信号差 >=200mV");
            chJson["e2_chb"] = "E2 零信号和满量程之间的信号差 >=200mV";
            old_e2_chb = 1;
        }
    }
    else
    {
        old_e2_chb = 0;
    }

    // 是否超量程   E3
    if(ci.e3_cha == 1)
    {
        cha_value->setText("E3");

        if(old_e3_cha == 0)
        {
            dbSaveAlarm(QString("CHA%1 %2").arg(fid + 1).arg(chaAddr),
                        "E3 零信号和满量程之间的信号差 3mV>n>2mV");
            chJson["e3_cha"] = "E3 零信号和满量程之间的信号差 3mV>n>2mV";
            old_e3_cha = 1;
        }
    }
    else
    {
        old_e3_cha = 0;
    }

    if(ci.e3_chb == 1)
    {
        chb_value->setText("E3");

        if(old_e3_chb == 0)
        {
            dbSaveAlarm(QString("CHB%1 %2").arg(fid + 1).arg(chbAddr),
                        "E3 零信号和满量程之间的信号差 3mV>n>2mV");
            chJson["e3_chb"] = "E3 零信号和满量程之间的信号差 3mV>n>2mV";
            old_e3_chb = 1;
        }
    }
    else
    {
        old_e3_chb = 0;
    }

    // 是否超量程   E4
    if(ci.e4_cha == 1)
    {
        cha_value->setText("E4");

        if(old_e4_cha == 0)
        {
            dbSaveAlarm(QString("CHA%1 %2").arg(fid + 1).arg(chaAddr), "E4 输入信号高于 +300mV");
            chJson["e4_cha"] = "E4 输入信号高于 +300mV";
            old_e4_cha = 1;
        }
    }
    else
    {
        old_e4_cha = 0;
    }

    if(ci.e4_chb == 1)
    {
        chb_value->setText("E4");

        if(old_e4_chb == 0)
        {
            dbSaveAlarm(QString("CHB%1 %2").arg(fid + 1).arg(chbAddr), "E4 输入信号高于 +300mV");
            chJson["e4_chb"] = "E4 输入信号高于 +300mV";
            old_e4_chb = 1;
        }
    }
    else
    {
        old_e4_chb = 0;
    }

    // 是否小心报警
    if(ci.state_c_cha == 0)
    {
        ac->setStyleSheet("background:darkred");
        chJson["state_c_cha"] = "";
        old_state_c_cha = 0;
    }
    else
    {
        ac->setStyleSheet("background:red");

        if(old_state_c_cha == 0)
        {
            dbSaveAlarm(QString("CHA%1 %2").arg(fid + 1).arg(chaAddr),
                        QString("CAUTION 小心报警 %1%2").arg(value_a).arg(unit_a));
        }

        old_state_c_cha = 1;
        chJson["state_c_cha"] = "CAUTION 小心报警";
        isAlarmSound = true;
    }

    if(ci.state_c_chb == 0)
    {
        bc->setStyleSheet("background:darkred");
        chJson["state_c_chb"] = "";
        old_state_c_chb = 0;
    }
    else
    {
        bc->setStyleSheet("background:red");

        if(old_state_c_chb == 0)
        {
            dbSaveAlarm(QString("CHB%1 %2").arg(fid + 1).arg(chbAddr),
                        QString("CAUTION 小心报警 %1%2").arg(value_b).arg(unit_b));
        }

        chJson["state_c_chb"] = "CAUTION 小心报警";
        old_state_c_chb = 1;
        isAlarmSound = true;
    }

    // 是否高报警
    if(ci.state_a_cha == 0)
    {
        ah->setStyleSheet("background:darkred");
        chJson["state_a_cha"] = "";
        old_state_a_cha = 0;
        //emit playWarningSound(false);
    }
    else
    {
        ah->setStyleSheet("background:red");

        if(old_state_a_cha == 0)
        {
            dbSaveAlarm(QString("CHA%1 %2").arg(fid + 1).arg(chaAddr),
                        QString("ALARM 高限报警 %1%2").arg(value_a).arg(unit_a));
        }

        //emit playWarningSound(true);
        chJson["state_a_cha"] = "ALARM 高限报警";
        old_state_a_cha = 1;
        isAlarmSound = true;
    }

    if(ci.state_a_chb == 0)
    {
        bh->setStyleSheet("background:darkred");
        chJson["state_a_chb"] = "";
        old_state_a_chb = 0;
        //emit playWarningSound(false);
    }
    else
    {
        bh->setStyleSheet("background:red");

        if(old_state_a_chb == 0)
        {
            dbSaveAlarm(QString("CHB%1 %2").arg(fid + 1).arg(chbAddr),
                        QString("ALARM 高限报警 %1%2").arg(value_b).arg(unit_b));
        }

        //emit playWarningSound(true);
        chJson["state_a_chb"] = "ALARM 高限报警";
        old_state_a_chb = 1;
        isAlarmSound = true;
    }

    // 是否预报警
    if(ci.state_w_cha == 0)
    {
        al->setStyleSheet("background:darkred");
        chJson["state_w_cha"] = "";
        old_state_w_cha = 0;
    }
    else
    {
        al->setStyleSheet("background:red");

        if(old_state_w_cha == 0)
        {
            dbSaveAlarm(QString("CHA%1 %2").arg(fid + 1).arg(chaAddr),
                        QString("WARNING 预报警 %1%2").arg(value_a).arg(unit_a));
        }

        chJson["state_w_cha"] = "WARNING 预报警";
        old_state_w_cha = 1;
        isAlarmSound = true;
    }

    //ci.state_w_chb = 1;

    if(ci.state_w_chb == 0)
    {
        bl->setStyleSheet("background:darkred");
        chJson["state_w_chb"] = "";
        old_state_w_chb = 0;
    }
    else
    {
        bl->setStyleSheet("background:red");

        if(old_state_w_chb == 0)
        {
            dbSaveAlarm(QString("CHB%1 %2").arg(fid + 1).arg(chbAddr),
                        QString("WARNING 预报警 %1%2").arg(value_b).arg(unit_b));
        }

        chJson["state_w_chb"] = "WARNING 预报警";
        old_state_w_chb = 1;
        isAlarmSound = true;
    }

    if(isAlarmSound)
    {
        emit playWarningSound();
    }

    //QDateTime dateTime = QDateTime::currentDateTime();
    QDateTime UTC(QDateTime::currentDateTimeUtc());
    QDateTime local(UTC.toLocalTime());
    qint64 numTime = local.toMSecsSinceEpoch();//当前时间转化为毫秒
    //chJson["ts"] = local.toSecsSinceEpoch();
    chJson["date"] = numTime;
    chJson["cardId"] = QString("Card%1").arg(fid + 1);
    chJson["chaAddr"] = chaAddr;
    chJson["chbAddr"] = chbAddr;
    QString mqtt_json = QJsonDocument(chJson).toJson(QJsonDocument::Compact);
    emit sendMqtt(fid + 1, mqtt_json);
    //qDebug() << mqtt_json;
}

// A通道单位符号 value = 0:ELE，1:ELEm，2:PPM，3:VOL，4:g/m3
void DragFrame::setUnitA(quint16 value)
{
    if(value <= 4)
    {
        unit_a = unitStr[value];
    }
    else
    {
        unit_a = "";
    }
}

// B通道单位符号 value = 0:ELE，1:ELEm，2:PPM，3:VOL，4:g/m3
void DragFrame::setUnitB(quint16 value)
{
    if(value <= 4)
    {
        unit_b = unitStr[value];
    }
    else
    {
        unit_b = "";
    }
}

//获取浓度值
double DragFrame::getValueA()
{
    return value_a;
}
//获取浓度值
double DragFrame::getValueB()
{
    return value_b;
}
//获取浓度单位
QString DragFrame::getUnitA()
{
    return unit_a;
}
//获取浓度单位
QString DragFrame::getUnitB()
{
    return unit_b;
}

int DragFrame::getModbusAddr()
{
    return fmodbusAddr;
}

bool DragFrame::getAlarming()
{
    return ci.state_a_cha || ci.state_a_chb;
}

void DragFrame::dbSaveRecode(QString chname, double value, QString unit)
{
    QDateTime dateTime = QDateTime::currentDateTime();
    uint numTime = dateTime.toTime_t();//当前时间转化为秒
    QSqlQuery query;
    QString sqlstr = QString("insert into concentration(chname,numtime,value,unit) "
                             "values('%1', %2, %3, '%4')").arg(chname).arg(numTime).arg(value).arg(unit);
    query.exec(sqlstr);
    //qDebug() << r << sqlstr;
}

void DragFrame::dbSaveAlarm(QString chname, QString alarmStr)
{
    QDateTime dateTime = QDateTime::currentDateTime();
    uint numTime = dateTime.toTime_t();//当前时间转化为秒
    QSqlQuery query;
    QString sqlstr = QString("insert into alarm(chname, numtime, numvalue) "
                             "values('%1', %2, '%3')").arg(chname).arg(numTime).arg(alarmStr);
    query.exec(sqlstr);
    // qDebug() << r << sqlstr;
}


